package liuwanghui.service.impl;

import liuwanghui.common.Result;
import liuwanghui.dto.LoginDTO;
import liuwanghui.dto.RegisterDTO;
import liuwanghui.dto.ResetPasswordDTO;
import liuwanghui.dto.VerifyIdentityDTO;
import liuwanghui.dto.response.LoginResponseDTO;
import liuwanghui.dto.response.UserInfoDTO;
import liuwanghui.mapper.UserMapper;
import liuwanghui.pojo.User;
import liuwanghui.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result login(LoginDTO loginDTO) {
        // 1. 参数校验
        if (!isValidUsername(loginDTO.getUsername())) {
            return Result.error("用户名格式不正确");
        }
        if (!isValidPassword(loginDTO.getPassword())) {
            return Result.error("密码格式不正确");
        }
        if (!isValidRole(loginDTO.getRole())) {
            return Result.error("角色类型不正确");
        }

        // 2. 查询用户
        User user = userMapper.findByUsername(loginDTO.getUsername());
        log.info("查询到的用户信息: {}", user);
        
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        // 3. 验证密码
        log.info("密码比较: {} vs {}", user.getPassword(), loginDTO.getPassword());
        if (!user.getPassword().equals(loginDTO.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 4. 验证角色
        log.info("角色比较: {} vs {}", user.getRoleType(), loginDTO.getRole());
        if (!user.getRoleType().equals(loginDTO.getRole())) {
            return Result.error("无效的角色类型");
        }

        // 5. 验证账号状态
        if (!"ACTIVE".equals(user.getStatus())) {
            return Result.error("该账号已被禁用");
        }

        // 6. 生成登录响应
        LoginResponseDTO responseDTO = new LoginResponseDTO();
        // TODO: 生成 JWT token
        responseDTO.setToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...");
        
        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setId(user.getUserId());
        userInfo.setUsername(user.getUsername());
        userInfo.setRole(user.getRoleType());
        userInfo.setRealName(user.getRealName());
        userInfo.setPhone(user.getPhone());
        userInfo.setEmail(user.getEmail());
        responseDTO.setUser(userInfo);

        // 7. 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateLastLoginTime(user);

        return Result.success(responseDTO);
    }

    private boolean isValidUsername(String username) {
        return username != null && username.matches("^[a-zA-Z0-9_]{4,16}$");
    }

    private boolean isValidPassword(String password) {
        return password != null && 
               password.matches("^[a-zA-Z0-9@#$%^&+=]{6,16}$");
    }

    private boolean isValidRole(String role) {
        return Arrays.asList("admin", "dealer", "farmer", "consumer").contains(role);
    }

    @Override
    public Result register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(registerDTO.getUsername()) != null) {
            return Result.error("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());
        user.setRoleType(registerDTO.getRole());
        
        userMapper.insert(user);
        return Result.success("注册成功");
    }

    @Override
    public Result resetPassword(ResetPasswordDTO resetPasswordDTO) {
        User user = userMapper.findByUsername(resetPasswordDTO.getUsername());
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        user.setPassword(resetPasswordDTO.getNewPassword());
        userMapper.updatePassword(user);
        return Result.success("密码重置成功");
    }

    @Override
    public Result verifyIdentity(VerifyIdentityDTO verifyIdentityDTO) {
        // 实现验证逻辑
        // 这里需要根据具体求实现，比如验证码校验等
        return Result.success("身份验证成功");
    }
} 